import QtQuick 2.0
import VPlay 2.0
// Plugins
//import VPlayPlugins.gamecenter 1.0
//import VPlayPlugins.flurry 1.0
//import VPlayPlugins.chartboost 1.1

// add this for Meego, to fix the portrait mode issue there
//import com.nokia.meego 1.0
//Page {

GameWindow {
  id: window
  licenseKey: "32577904E60710A6BDC2C0C22D259280026DCF61A2C3809476B184505DDEF28260BF5554BE4B1094CA7A27A4B5420A07A8C9ACC08F74687D694E6DD31636F566DACBF145CCB74F1E569B37F8B150F769184B69A94F6D918533F8934B38E9AA5F5DE58366D480DCC9D49DBFB3C4ECF192638FB032EDDADE5E43FFAFCE10A1EC33266F08700A4654359F7597A1DC041604B336A87B58453D6D387529159CADFB7729B0DFB6828DF6BD141FDC28CC00CD359B60555E0425E7951F39431B419BAEF04FBC2CA1C0B3130C7C32697CBBF5C7B162A7E2815CAC76DBA6CDCC4FB14237D110CE922756C7801889FEEF083E2BE2F295B7CC4FD1C65C343E50F575236F85103B850F2DAED736DBAED74818ED490E33833B85DA57B30E4FF4C803ADED6AE389"
  // depending on which window size is defined as start resolution here, the corresponding image sizes get loaded here! so for testing hd2 images, at least use factor 3.5
  // the window size can be changed at runtime by pressing the keys 1-6 (see GameWindow.qml)
  width: 320*2//*1.5 // for testing on desktop with the highest res, use *1.5 so the -hd2 textures are used
  height: 480*2//*1.5

  // WRONG: to fix the portrait mode issue on Meego, we could set it to this and rotate by 90 degrees, and also set the SceneBase to 480x320
  // this doesnt work, because anchoring is wrong then! (i.e. when anchoring to bottom, for instance, it is not correctly anchored as it would need to be anchored to the left
//  width: 480*2
//  height: 320*2
//  rotation: 90

  // for better readability of the fps for QML renderer
//  fpsTextItem.color: "white"

  // all properties assigned here are accessible from all entities!
  // the reason for that is, because entities get created through the
  // EntityManager here in this GameWindow,
  // and only the parent items of the item where it was created are
  // known to the dynamically created entities
  property alias level: scene.level
  property alias player: scene.player // this works, when player is defined as alias in scene
 // property alias chartboost: chartboost
  property alias preferences: preferencesScene.preferences

  // for loading the stored highscore and displaying on GameOverScreen when a new highscore is reached
  // these get accessed from the MainScene and the SpacyJumpScene
  property int maximumHighscore: 0
  property int lastScore: 0
  Component.onCompleted: {
    var storedScore = settings.getValue("maximumHighscore");
    // if first-time use, nothing can be loaded and storedScore is undefined
    if(storedScore)
      maximumHighscore = storedScore;

    // Authenticate player to gamecenter
    //gameCenter.authenticateLocalPlayer();

    if(preferences.getValue("firstStart") == undefined) {
      preferences.setValue("firstStart", true)
    }

    // this may be added to deactivate sounds in debug builds
//    if(system.debugBuild) {
//      settings.ignoredPropertiesForStoring = ["soundEnabled"]
//      settings.soundEnabled = false
//    }
  }
  onMaximumHighscoreChanged: {
    var storedScore = settings.getValue("maximumHighscore");
    // if not stored anything yet, store the new value
    // or if a new highscore is reached, store that
    if(!storedScore || maximumHighscore > storedScore) {
      console.debug("stored improved highscore from", storedScore, "to", maximumHighscore);
      settings.setValue("maximumHighscore", maximumHighscore);
    }

    // Post highscore to gameCenter; TODO: Post later if gamecenter is not available?
//    if (gameCenter.authenticated)
//      gameCenter.reportScore(maximumHighscore);
  }

  // use BackgroundMusic for long-playing background sounds
  BackgroundMusic {
    id: backgroundMusic
    source: system.isPlatform(System.Meego) || system.isPlatform(System.Symbian) ? "snd/purple_hills.ogg" : "snd/purple_hills.wav"

    // it is auto-played because autoplay is set to true by default!
  }

  // Custom font loading of ttf fonts
  FontLoader {
    id: fontHUD
    source: "fonts/sing.ttf"
  }

//  // Works only with iOS bundle identifier com.alexleutgoeb.ios.chickenbreakout!
//  GameCenter {
//    id: gameCenter

//    // Use highscore from GameCenter if it is higher than our local one
//    onAuthenticatedChanged: {
//      if (authenticated === true) {
//        // For debugging only
//        // resetAchievements();

//        var gameCenterScore = getGameCenterScore();
//        if (gameCenterScore > maximumHighscore)
//          maximumHighscore = gameCenterScore;
//      }
//    }
//  }

  // Flurry is only avaialable on iOS and Android
//  Flurry {
//    id: flurry
//    // this is the app key for the SpacyJump-SDK-Demo, it is not the one used for the real app (which is not official)
//    apiKey: "9PH383W92BYDK6ZYVSDV"
//  }

//  Chartboost {
//      id: chartboost
//      appId: "529785ac2d42da443f2a3e6f"
//      appSignature: "276a6170b1635146fca95cf49d25ebbd388fbfd1"

//      onInterstitialCached: {
//          console.log("interstitial successfully downloaded")
//      }

//      onInterstitialFailedToLoad: {
//          console.log("no interstitial downloaded")
//      }
//  }

  // this scene is set to visible when loaded initially, so its opacity value gets set to 1 in a PropertyChange below
  MainScene {
    id: mainScene
    //        visible: false - when opacity is 0, visible gets set to false in SceneBase
    opacity: 0
  }

  SpacyJumpScene {
    id: scene
    //        visible: false - when opacity is 0, visible gets set to false in SceneBase
    opacity: 0
    onVisibleChanged: console.debug("GameScene changed visible to", visible)
  }

  GameOverScene {
    id: gameOverScene
    //        visible: false - when opacity is 0, visible gets set to false in SceneBase
    opacity: 0
  }

  CreditsScene {
    id: creditsScene
    //        visible: false - when opacity is 0, visible gets set to false in SceneBase
    opacity: 0
  }

  PreferencesScene {
    id: preferencesScene
    //        visible: false - when opacity is 0, visible gets set to false in SceneBase
    opacity: 0
  }

  // for creating & removing entities
  EntityManager {
    id: entityManager
    entityContainer: scene.entityContainer    
    poolingEnabled: true // entity pooling works since version 0.9.4, so use it
  }

  // this gets used for analytics, to know which state was ended before
  property string lastActiveState: ""

  onStateChanged: {

    console.debug("ChickenBreakoutMain: changed state to", state)

    if(state === "main")
      activeScene = mainScene;
    else if(state === "game")
      activeScene = scene;
    else if(state === "gameOver")
      activeScene = gameOverScene;
    else if(state === "credits")
      activeScene = creditsScene;
    else if(state === "preferences")
      activeScene = preferencesScene;

    if(lastActiveState === "main") {
//      flurry.endTimedEvent("Display.Main");
    } else if(lastActiveState === "game") {
      //flurry.endTimedEvent("Display.Game");

      // NOTE: Android doesnt support endTimedEventWithParams yet!?! http://stackoverflow.com/questions/12205860/android-flurry-and-endtimedevent
      //flurry.endTimedEvent("Display.Game", { "score": lastScore, "collectedCorns" : player.bonusScore, "scoreForCorns": player.bonusScore*player.bonusScoreForCoin });
      // thus emit them with own events

//      flurry.logEvent("Game.Finished", { "score": lastScore, "collectedCorns" : player.bonusScore, "scoreForCorns": player.bonusScore*player.bonusScoreForCoin })

    } else if(lastActiveState === "gameOver") {
//      flurry.endTimedEvent("Display.GameOver");
    } else if(lastActiveState === "credits") {
//      flurry.endTimedEvent("Display.Credits");
    }

    if(state === "main") {
//      flurry.logTimedEvent("Display.Main");
    } else if(state === "game") {
//      flurry.logTimedEvent("Display.Game");
    } else if(state === "gameOver") {
      flurry.logTimedEvent("Display.GameOver");
    } else if(state === "credits") {
//      flurry.logTimedEvent("Display.Credits");
    }

    lastActiveState = state;
  }

  // use state game for the beginning for debugging the game logic, as the game state gets entered in the beginning
  state: "main"
  // use one of the following states to start with another state when launching the game
  //    state: "game"
  //state: "gameOver"

  // these states are switched when the play button is pressed in MainScene, when the game is lost and when the Continue button is pressed in GameOverScene
  states: [
    State {
      name: "main"
      // by switching the propery to 1, which is by default set to 0 above, the Behavior defined in SceneBase takes care of animating the opacity of the new Scene from 0 to 1, and the one of the old scene from 1 to 0
      PropertyChanges { target: mainScene; opacity: 1}

    },
    State {
      name: "game"
      PropertyChanges { target: scene; opacity: 1}
      StateChangeScript {
        script: {
          console.debug("entered state 'game'")
          console.debug("GameScene.visible:", scene.visible)

          scene.enterScene();
        }
      }
    },
    State {
      name: "gameOver"
      PropertyChanges { target: gameOverScene; opacity: 1}
      StateChangeScript {
        script: {
          console.debug("entered state 'gameOver'")
          gameOverScene.enterScene();
        }
      }
    },
    State {
      name: "credits"
      PropertyChanges { target: creditsScene; opacity: 1}

    },
      State {
        name: "preferences"
        PropertyChanges { target: preferencesScene; opacity: 1}

      }
  ]
}
//} // add this when building for MeeGo
